const {
	Service
} = require('uni-cloud-router')
const {
	getTodayTime,
} = require('../util');
module.exports = class AppService extends Service {
	constructor(ctx) {
		super(ctx)
		this.userCollection = this.db.collection('uni-id-users')
		this.scoreDayStatisticsCollection = this.db.collection('uni-id-score-day-statistics')
	}
	/**
	 * 获取最新分红
	 * @param {Object} day
	 */
	async getNewMoney(day) {
		const cmd = this.db.command;
		let {
			data
		} = await this.scoreDayStatisticsCollection.where({
			open_time: cmd.lt(Date.now()),
			day: cmd.gt(day),
			money: cmd.gt(0),
			status: 1,
		}).orderBy("day", "asc").get();
		return data;
	}

	/**
	 * 系统每日积分获取统计
	 * @param {Object} amount
	 * @param {Object} day
	 */
	async setScoreDayStatistics(amount, field = "value", day = 0) {
		amount = parseFloat(amount);
		if (amount > 0) {
			if (!day) {
				day = getTodayTime(0, true);
			}
			const cmd = this.db.command;
			const {
				updated
			} = await this.scoreDayStatisticsCollection.where({
				day
			}).update({
				[field]: cmd.inc(amount)
			});
			if (!updated) {
				//需要新增
				await this.scoreDayStatisticsCollection.add({
					day,
					[field]: amount
				});
			}
		}
	}

	/**
	 *  修复积分总计，比较耗费资源
	 */
	async repair(id, day) {
		const cmd = this.db.command;
		const $ = cmd.aggregate;
		let {
			data
		} = await this.userCollection.aggregate().match({
			["score_log." + day]: cmd.gt(0)
		}).group({
			_id: null,
			totalScore: $.sum(`$score_log.${day}`)
		}).end();
		if (data.length > 0) {
			console.log(data[0]);
			await this.scoreDayStatisticsCollection.doc(id).update({
				"value": data[0].totalScore
			})
		}
		return data;
	}
}
